package com.css.fxfzcpxx.modules.websocket;

import com.css.fxfzcpxx.base.response.ResponseCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: xzy
 * @CreateTime: 2023/11/28 12:01
 * @Description: WebSocket管理器
 */
@Slf4j
@Component
@Data
public class WebSocketManager {

    private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    public void addSession(WebSocketSession session) {
        sessions.add(session);
    }

    public void removeSession(WebSocketSession session) {
        sessions.remove(session);
    }

    public void broadcastMessage(String message,String moduleType) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        SendMessage sendMessage=new SendMessage();
        sendMessage.setMessage(message);
        sendMessage.setModuleType(moduleType);
        String jsonMessage;




        jsonMessage = objectMapper.writeValueAsString(sendMessage);


        for (WebSocketSession session : sessions) {
            session.sendMessage(new TextMessage(jsonMessage));

        }
    }


}

